import React from 'react';
import Mixins from '@/components/Common/mixin';
import styles from '@/pages/riskControl/deviantWithdrawReview/details/index.less';
import connectFn from '@/utils/connectFn';
import { types } from '@/utils/utils';
import constant from '@/const';
import { StateType } from '@/common-typings';
import _ from 'lodash';
import { formatText } from '@/components/CreateTable/utils';
import {
  Flag,
  dateObj,
  DefaultTitle,
} from '@/pages/riskControl/deviantWithdrawReview/details/utils';

import {
  getFinanceData,
  getAccountBalance,
  getTradingData,
  getBettingData,
  getBackCardData,
  getLoginData,
} from './applicantConfig';

const { SUCCESS_CODE } = constant;

@connectFn(
  [],
  [
    'getBalanceManageBalance',
    'getReportStationTrendUserFund',
    'getUserManageListBalanceHistory',
    'getGameManageListBet',
    'getUserBankCardManageListUser',
    'getUserLoginDetailLog',
  ],
)
class Applicant extends Mixins {
  state = {
    balanceLoading: true,
    financeLoading: true,
    tradingLoading: true,
    bettingLoading: true,
    bankCardLoading: true,
    loginLoading: true,
    balanceList: [],
    financeList: [],
    tradingList: [],
    bettingList: [],
    bankCardList: [],
    loginList: [],
    financeDate: 'today',
    tradingDate: 'today',
    bettingDate: 'today',
    loginDate: 'today',
    tradingPagination: this.defaultPagination,
    bettingPagination: this.defaultPagination,
    loginPagination: this.defaultPagination,
  };

  componentDidMount(): void {
    this.requestAccountBalance();
    this.requestFinanceData();
    this.requestTradingData();
    this.requestBettingData();
    this.requestBankData();
    this.requestLoginData();
  }

  /**
   * 获取账户余额
   */
  requestAccountBalance = () => {
    const { currentRow, getBalanceManageBalance } = this.props;
    const balanceList = _.cloneDeep(constant.TRANSFER_PLATFORMS).map((item: StateType) => ({
      ...item,
      balance: 0,
      username: '',
    }));

    this.changePageLoading({ balanceLoading: true });
    // 防止数据缓存
    this.changeState({ balanceList: [] });

    getBalanceManageBalance({
      userId: currentRow.userId,
    }).then((res: StateType) => {
      const { code, data } = res;
      if (code === SUCCESS_CODE && data && types(data) === 'array') {
        balanceList.forEach((balanceItem: StateType) => {
          data.forEach((dataItem: StateType) => {
            if (balanceItem.value === dataItem.channelId) {
              balanceItem.balance = dataItem.balance;
              balanceItem.username = dataItem.username;
            }
          });
        });
        const balanceObj: StateType = {
          platform: '余额',
        };
        const usernameObj: StateType = {
          platform: '账户名',
        };

        balanceList.forEach((item: StateType) => {
          balanceObj[item.value] = formatText(item.balance, { formatAmount: true });
          usernameObj[item.value] = item.username;
        });

        this.changeState({ balanceList: [balanceObj, usernameObj] });
      }
      this.changePageLoading({ balanceLoading: false });
    });
  };

  /**
   * 获取账户财务信息
   */
  requestFinanceData = () => {
    const { getReportStationTrendUserFund, currentRow } = this.props;
    const { financeDate } = this.state;

    let params: StateType = { userId: currentRow.userId };
    const dataArr = dateObj[financeDate];
    if (dataArr.length) {
      params = {
        ...params,
        startTime: formatText(dataArr[0], { formatTimeStamp: true }),
        endTime: formatText(dataArr[1], { formatTimeStamp: true }),
      };
    }

    this.changePageLoading({ financeLoading: true });
    this.changeState({ financeList: [] });

    getReportStationTrendUserFund(params).then((res: StateType) => {
      const { code, data } = res;
      if (code === SUCCESS_CODE && data && types(data) === 'object') {
        console.log(data);
        this.changeState({ financeList: [data] });
      }

      this.changePageLoading({ financeLoading: false });
    });
  };

  /**
   * 请求交易信息
   */
  requestTradingData = () => {
    const { getUserManageListBalanceHistory, currentRow } = this.props;
    const { tradingDate, tradingPagination } = this.state;

    let params: StateType = {
      userId: currentRow.userId,
      // 交易类型
      orderType: [1, 2, 3, 4, 5, 6, 10, 11, 14].join(','),
      page: tradingPagination.page,
      size: tradingPagination.size,
    };
    const dataArr = dateObj[tradingDate];
    if (dataArr.length) {
      params = {
        ...params,
        startTime: formatText(dataArr[0], { formatTimeStamp: true }),
        endTime: formatText(dataArr[1], { formatTimeStamp: true }),
      };
    }

    this.changePageLoading({ tradingLoading: true });
    this.changeState({ tradingList: [] });

    getUserManageListBalanceHistory(params).then((res: StateType) => {
      const { code, data } = res;
      if (code === SUCCESS_CODE && data && types(data) === 'object') {
        const list = data.list || [];
        list.forEach((item: StateType, index: number) => {
          item.index = index + 1;
        });
        this.setState(preState => ({
          ...preState,
          tradingList: data.list || [],
          tradingPagination: {
            ...preState.tradingPagination,
            // page: data.pageNum || this.defaultPagination.page,
            // size: data.pageSize || this.defaultPagination.size,
            total: data.total,
          },
        }));
      }

      this.changePageLoading({ tradingLoading: false });
    });
  };

  /**
   * 下注纪录
   */
  requestBettingData = () => {
    const { getGameManageListBet, currentRow } = this.props;
    const { bettingDate, bettingPagination } = this.state;

    const status: any[] = [];
    const gamePlaform: any[] = [];
    constant.NOTE_STATUS.forEach((item: StateType) => {
      status.push(item.value);
    });

    constant.GAME_ID.forEach((item: StateType) => {
      gamePlaform.push(item.gamePlatformId);
    });

    let params: StateType = {
      username: currentRow.username,
      page: bettingPagination.page,
      size: bettingPagination.size,
      status: status.join(','),
      // gamePlatformId: gamePlaform.join(','),
      gamePlatformId: [
        1001,
        1004,
        1003,
        7002,
        4003,
        2001,
        10006,
        11006,
        2003,
        13001,
        17003,
        23004,
        18005,
        16002,
      ].join(','),
      isFake: 0,
    };
    const dataArr = dateObj[bettingDate];
    if (dataArr.length) {
      params = {
        ...params,
        startTime: formatText(dataArr[0], { formatTimeStamp: true }),
        endTime: formatText(dataArr[1], { formatTimeStamp: true }),
      };
    }

    this.changePageLoading({ bettingLoading: true });
    this.changeState({ bettingList: [] });

    getGameManageListBet(params).then((res: StateType) => {
      const { code, data } = res;
      if (code === SUCCESS_CODE && data && types(data) === 'object') {
        // this.changeState({ financeList: [data] })
        this.setState(preState => ({
          ...preState,
          bettingList: data.list || [],
          bettingPagination: {
            page: data.pageNum || this.defaultPagination.page,
            size: data.pageSize || this.defaultPagination.size,
            total: data.total,
          },
        }));
      }

      this.changePageLoading({ bettingLoading: false });
    });
  };

  /**
   * 银行信息
   */
  requestBankData = () => {
    const { getUserBankCardManageListUser, currentRow } = this.props;
    const params: StateType = { userId: currentRow.userId };

    this.changePageLoading({ bankCardLoading: true });
    this.changeState({ bankCardList: [] });

    getUserBankCardManageListUser(params).then((res: StateType) => {
      const { code, data } = res;
      if (code === SUCCESS_CODE && data && types(data) === 'array') {
        this.changeState({ bankCardList: data });
      }

      this.changePageLoading({ bankCardLoading: false });
    });
  };

  /**
   * 会员登入日志
   */
  requestLoginData = () => {
    const { getUserLoginDetailLog, currentRow } = this.props;
    const { loginDate, loginPagination } = this.state;

    let params: StateType = {
      userName: currentRow.username,
      page: loginPagination.page,
      size: loginPagination.size,
    };
    const dataArr = dateObj[loginDate];
    if (dataArr.length) {
      params = {
        ...params,
        stime: dataArr[0],
        etime: dataArr[1],
      };
    }

    this.changePageLoading({ loginLoading: true });
    this.changeState({ loginList: [] });

    getUserLoginDetailLog(params).then((res: StateType) => {
      const { code, data } = res;
      if (code === SUCCESS_CODE && data && types(data) === 'object') {
        const list = data.list || [];
        list.forEach((item: StateType, index: number) => {
          item.index = index + 1;
        });
        this.setState(preState => ({
          ...preState,
          loginList: data.list || [],
          loginPagination: {
            ...preState.loginPagination,
            // page: preState.loginPagination.pageNum || this.defaultPagination.page,
            // size: preState.loginPagination.pageSize || this.defaultPagination.size,
            total: data.total,
          },
        }));
      }

      this.changePageLoading({ loginLoading: false });
    });
  };

  /**
   * button group 改变
   * @param e
   */
  handleFinanceButton = (e: StateType) => {
    this.changeState({ financeDate: e.target.value }, this.requestFinanceData);
  };

  /**
   * button group 改变
   * @param e
   */
  handleTradingButton = (e: StateType) => {
    this.changeState({ tradingDate: e.target.value }, this.requestTradingData);
  };

  /**
   * button group 改变
   * @param e
   */
  handleBettingButton = (e: StateType) => {
    this.changeState({ bettingDate: e.target.value }, this.requestBettingData);
  };

  /**
   * button group 改变
   * @param e
   */
  handleLoginButton = (e: StateType) => {
    this.changeState({ loginDate: e.target.value }, this.requestLoginData);
  };

  /**
   * 交易分页变化
   * @param param
   */
  changeTradingPage = (param: StateType) => {
    this.setState(
      preState => ({
        ...preState,
        tradingPagination: {
          ...preState.tradingPagination,
          page: param.pageNum,
          size: param.pageSize,
        },
      }),
      () => {
        this.requestTradingData();
      },
    );
  };

  changeBettingPage = (param: StateType) => {
    this.setState(
      preState => ({
        ...preState,
        bettingPagination: {
          ...preState.bettingPagination,
          page: param.pageNum,
          size: param.pageSize,
        },
      }),
      () => {
        this.requestBettingData();
      },
    );
  };

  changeLoginPage = (param: StateType) => {
    this.setState(
      preState => ({
        ...preState,
        loginPagination: {
          ...preState.loginPagination,
          page: param.pageNum,
          size: param.pageSize,
        },
      }),
      () => {
        this.requestLoginData();
      },
    );
  };

  /**
   * 账户详情
   */
  renderAccountInfo = () => {
    const { currentRow, parentAgent } = this.props;
    return (
      <div style={{ paddingBottom: '20px' }}>
        <Flag>账户详情</Flag>
        <DefaultTitle parentAgent={parentAgent} username={currentRow.username} />
        {getFinanceData(this)}
        {getAccountBalance(this)}
      </div>
    );
  };

  /**
   * 交易概况
   */
  renderTradingInfo = () => {
    const { currentRow } = this.props;
    const isUser = currentRow.userType === 0;
    return (
      <div>
        <Flag>{`${isUser ? '会员' : '代理'}账户交易概况`}</Flag>
        {getTradingData(this)}
      </div>
    );
  };

  /**
   * 下注概况
   */
  renderBettingInfo = () => {
    const { currentRow } = this.props;
    const isUser = currentRow.userType === 0;
    return (
      <div>
        <Flag>{`${isUser ? '会员' : '代理'}下注概况`}</Flag>
        {getBettingData(this)}
      </div>
    );
  };

  /**
   * 银行信息
   */
  renderBankCardInfo = () => (
    <div>
      <Flag>银行信息</Flag>
      {getBackCardData(this)}
    </div>
  );

  /**
   * 会员登入行为
   */
  renderLoginInfo = () => {
    const { currentRow } = this.props;
    const isUser = currentRow.userType === 0;
    return (
      <div>
        <Flag>{`${isUser ? '会员' : '代理'}登入行为`}</Flag>
        {getLoginData(this)}
      </div>
    );
  };

  render() {
    return (
      <div className={styles['content-box']}>
        {this.renderAccountInfo()}
        {this.renderTradingInfo()}
        {this.renderBettingInfo()}
        {this.renderBankCardInfo()}
        {this.renderLoginInfo()}
      </div>
    );
  }
}

export default Applicant;
